<script setup>
import {reactive, ref, onMounted} from 'vue';
import router from '@/router'
import api from '@/api/index.js' // 引入API模块

const activeIndex = ref('1')
const userRole = ref(2) // 默认普通用户


// 当前登录用户信息（从sessionStorage获取）
const loginAdmin = ref({
  uname: sessionStorage.getItem("uname") || "未登录", // ✅ 直接使用字符串
  urole: parseInt(sessionStorage.getItem("urole")) || 2,
});
// 初始菜单数据
const fullMenuData = [
  {
    name: '药物管理', icon: 'Document', children: [
      {name: '药品信息列表', icon: 'Document', path: "/drug"},
      {name: '药品分类列表', icon: 'Menu', path: "/category"},
      {name: '数据统计', icon: 'DataAnalysis', path: "/charts"},
    ]
  },
  {
    name: '仓库管理', icon: 'House', children: [
      {name: '仓库信息列表', icon: 'Files', path: "/warehouse"},
    ]
  },
  {
    name: '交易管理', icon: 'ShoppingCart', children: [
      {name: '订单信息列表', icon: 'Tickets', path: "/orders"},
      {name: '消费者信息列表', icon: 'UserFilled', path: "/customer"},
    ]
  },
  {
    name: '信息管理', icon: 'Bell', children: [
      {name: '信息通知', icon: 'Message', path: "/messages"},
    ]
  },
  {
    name: '供应商管理', icon: 'List', children: [
      {name: '供应商信息列表', icon: 'List', path: "/supplier"},
      {name: '采购记录', icon: 'Tickets', path: "/purchase"},
    ]
  },
  {
    name: '管理员管理', icon: 'User', children: [
      {name: '用户管理列表', icon: 'Setting', path: "/user"},
    ]
  },
];

// 根据权限过滤后的菜单
const menuData = ref([])

onMounted(() => {
  isLogin();
});

async function isLogin() {
  const token = sessionStorage.getItem('token');
  if (token) {
    try {
      const uname = sessionStorage.getItem("uname") || "未登录";
      const urole = parseInt(sessionStorage.getItem("urole")) || 2;
      loginAdmin.value = { uname, urole };
      userRole.value = urole;

      filterMenuByRole();
    } catch (error) {
      logout();
    }
  } else {
    router.push('/login');
  }
}


// 根据用户权限过滤菜单
function filterMenuByRole() {
  if (userRole.value === 1) { // 管理员
    menuData.value = [...fullMenuData];
  } else { // 普通用户
    menuData.value = fullMenuData.filter(item =>
        item.name !== '管理员管理' &&
        item.name !== '数据统计' // 普通用户也不看数据统计
    );
  }
}

// 用户下拉菜单的点击
function handleSelect(key) {
  if (key === 'logout') {
    logout();
  }
}

// 左侧菜单动作
function handleMenu(key) {
  if (key) {
    router.push(key);
  }
}

function logout() {
  // 清除Token和用户信息
  sessionStorage.removeItem('token');
  sessionStorage.removeItem('urole');
  sessionStorage.removeItem('uname');
  // 跳转到登录
  router.push('/login')
}

// 左侧菜单展开折叠
const isCollapse = ref(false);
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-aside :width="isCollapse ? '64px' : '200px'">
        <div class="menu-toggle" @click="isCollapse=!isCollapse">
          <el-icon>
            <Expand v-if="isCollapse"></Expand>
            <Fold v-else></Fold>
          </el-icon>
        </div>
        <!-- 管理员信息卡片 -->
        <div class="admin-info-card" v-if="!isCollapse">
          <div class="admin-header">
            <el-icon class="admin-icon"><User /></el-icon>
            <div class="admin-titles">
              <!-- 显示实际用户名 -->
              <div class="admin-title">{{ loginAdmin.uname || '未登录' }}</div>
              <div class="admin-subtitle">{{ userRole === 1 ? '系统管理员' : '普通用户' }}</div>
            </div>
          </div>
          <div class="admin-stats">
            <div class="stat-item">
              <div class="stat-number">128</div>
              <div class="stat-label">药品</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">12</div>
              <div class="stat-label">仓库</div>
            </div>
            <div class="stat-item">
              <!-- 管理员显示用户数 -->
              <div class="stat-number">{{ userRole === 1 ? '50' : '0' }}</div>
              <div class="stat-label">用户</div>
            </div>
          </div>
        </div>

        <!-- 动态菜单 -->
        <el-menu
            active-text-color="#4a9df6"
            background-color="#0c1d40"
            class="el-menu-vertical-demo"
            :default-active="$route.path"
            text-color="#fff"
            :collapse="isCollapse"
            @select="handleMenu"
        >
          <el-sub-menu v-for="(menu, index) in menuData" :index="index.toString()" :key="index">
            <template #title>
              <component
                  class="icons"
                  :is="menu.icon"
                  style="width: 1em; height: 1em; margin-right: 8px">
              </component>
              <span>{{ menu.name }}</span>
            </template>
            <el-menu-item v-for="(child, ind) in menu.children" :index="child.path" :key="ind">
              <el-icon>
                <component
                    :is="child.icon">
                </component>
              </el-icon>
              <span>{{ child.name }}</span>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>

      <el-container>
        <el-header>
          <el-menu
              :default-active="activeIndex"
              class="el-menu-demo"
              mode="horizontal"
              :ellipsis="false"
              background-color="#ffffff"
              text-color="#2c3e50"
              active-text-color="#4a9df6"
              @select="handleSelect"
          >
            <el-menu-item index="0">
              <img class="logo" src="@/static/OIP-C (1).webp" alt="药物管理系统" />
              <span class="app-title">药物管理系统</span>
            </el-menu-item>
            <div class="flex-grow"/>
            <el-sub-menu index="1">
              <template #title>
                <el-icon><User/></el-icon>
                <!-- 显示当前用户名 -->
                {{ loginAdmin.uname || '未登录' }}
              </template>
              <el-menu-item index="logout">
                退出
                <el-icon><SwitchButton/></el-icon>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-header>

        <el-main style="background-color: #f8fbfe;">
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>



<style scoped>

.admin-info-card {
  background: linear-gradient(135deg, #1a2b56, #0c1d40);
  border-radius: 8px;
  padding: 15px;
  margin: 0 12px 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  color: white;
  border: 1px solid rgba(74, 157, 246, 0.3);
}

.admin-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.admin-icon {
  font-size: 32px;
  color: #4a9df6;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  padding: 8px;
  margin-right: 12px;
}

.admin-titles {
  line-height: 1.3;
}

.admin-title {
  font-size: 16px;
  font-weight: 600;
}

.admin-subtitle {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.7);
}

.admin-stats {
  display: flex;
  justify-content: space-between;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 18px;
  font-weight: bold;
  color: #4a9df6;
}

.stat-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 3px;
}

/* 调整折叠按钮位置 */
.menu-toggle {
  height: 50px;
  margin-bottom: 15px;
}
.flex-grow {
  flex-grow: 1;
}

.common-layout,
.el-container {
  height: 100%;
}

.el-header {
  --el-header-padding: 0 20px;
  --el-header-height: 70px; /* 更紧凑的头部 */
  box-sizing: border-box;
  flex-shrink: 0;
  height: var(--el-header-height);
  padding: var(--el-header-padding);
  box-shadow: 0 2px 8px rgba(74, 157, 246, 0.1); /* 医疗蓝色阴影 */
  background-color: #fff;
}

.el-menu--horizontal {
  height: 70px;
  background-color:#a3c8f0;
}

.el-aside {
  background-color: #0c1d40; /* 深蓝背景保持专业感 */
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

.el-main {
  padding: 0px;
}

.el-menu {
  border-width: 0px;
}

.el-menu-item {
  font-size: 15px;
}

.el-menu-demo {
  box-shadow: 0 2px 8px rgba(74, 157, 246, 0.1);
}

.el-sub-menu__title {
  font-size: 15px;
}

.menu-toggle {
  height: 60px;
  line-height: 60px;
  text-align: right;
  color: #fff;
  font-size: 20px;
  margin-right: 24px;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-toggle:hover {
  color: #4a9df6;
}

.logo {
  height: 45px;
  margin-right: 10px;
  filter: hue-rotate(160deg); /* 调整logo颜色为医疗蓝色系 */
}

.app-title {
  padding-left: 50px;
  font-size: 22px;
  color: #2c3e50;
  font-weight: 600;
  letter-spacing: 1px;
}

/* 菜单激活状态指示器 */
.el-menu-item.is-active {
  background-color: rgba(74, 157, 246, 0.1) !important;
  border-left: 3px solid #4a9df6;
}
</style>